<template>
  <div>
    <div class="lists_tit">
    </div>
    <div class="lists-box">
      <div class="list_title">新闻资讯列表</div>
      <el-button v-if="isShow" size="small" type="primary" @click="zxAdd">新增文章</el-button>
      <el-select v-model="query.type" clearable placeholder="请选择资讯类型" @change="search">
        <el-option
          v-for="item in options"
          :key="item.label"
          :label="item.dictvalue"
          :value="item.label">
        </el-option>
      </el-select>
      <el-input
        v-model="query.title"
        class="input-with-select"
        clearable
        placeholder="请输入标题"
      >
        <el-button
          slot="append"
          icon="el-icon-search"
          @click="search"
        ></el-button>
      </el-input>
    </div>
    <el-table :data="tableData" stripe style="width: 100%">
      <el-table-column label="标题" prop="title" width="180">
      </el-table-column>
      <el-table-column label="资讯类型" prop="type">
        <template slot-scope="scope">
          {{
            scope.row.type === 1 ? '社会资讯' : scope.row.type === 2 ? '机关发文' : scope.row.type === 3 ? '操作指南' : '未知分类'
          }}
        </template>
      </el-table-column>
      <el-table-column label="创建人" prop="updateBy"></el-table-column>
      <el-table-column label="创建时间" prop="createTime"></el-table-column>
      <el-table-column
        fixed="right"
        label="操作"
        width="150">
        <template slot-scope="scope">
          <el-button size="small" type="text" @click="routerDetails(scope.row)">查看</el-button>
          <el-button v-if="isShow" size="small" type="text" @click="editArticle(scope.row)">编辑</el-button>
          <el-button v-if="isShow" size="small" type="text" @click="delBtn(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :current-page="query.current"
      :page-size="query.size"
      :page-sizes="[10, 20, 30, 40]"
      :total="totalCount"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    >
    </el-pagination>
    <!--    新增弹窗-->
    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisibleXz" width="1000px">
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        class="demo-ruleForm"
        label-width="80px"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="ruleForm.title"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <vue-editor v-model="ruleForm.content"></vue-editor>
        </el-form-item>
        <el-form-item label="资讯类型" prop="type">
          <el-select v-model="ruleForm.type" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.label"
              :label="item.dictvalue"
              :value="item.label">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上传附件">
          <el-upload
            :action="xhDomain + '/api/dataFile/add/'+ uuid"
            :before-remove="beforeRemove"
            :before-upload="beforeUpload"
            :file-list="fileList"
            :headers="headers"
            :on-error="handleError"
            :on-exceed="handleExceed"
            :on-preview="handlePreview"
            :on-progress="handleProgress"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            class="upload-demo"
            multiple
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisibleXz = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {VueEditor} from "vue2-editor";
import Quill from 'quill';

const Parchment = Quill.import('parchment');
const IndentStyle = new Parchment.Attributor.Style('textIndent', 'text-indent', {
  scope: Parchment.Scope.BLOCK,
  whitelist: ['2em', '3em']
});

Quill.register(IndentStyle, true);
import {
  interactList,
  getZxtype,
  getZxadd,
  getZxList,
  getZxDelete,
  getZxEdit,
  getZxDetail,
  issjj
} from "../../../utils/httpUtils";

export default {
  components: {VueEditor},
  data() {
    return {
      uuid: '',
      isShow: false,
      ids: '',
      dialogTitle: '',
      fileLocations: [],
      options: [],
      editorOptions: {
        modules: {
          toolbar: [
            [{'header': [1, 2, 3, false]}],  // 标题选项
            ['bold', 'italic', 'underline'],  // 粗体、斜体、下划线
            [{'list': 'ordered'}, {'list': 'bullet'}],  // 列表
            [{'textIndent': ['2em', false]}],  // 自定义的首行缩进选项
            ['clean']  // 清除格式
          ]
        }
      },
      xhDomain: xhDomain,
      headers: {Authorization: JSON.parse(localStorage.getItem('token'))},
      dialogFormVisibleXz: false,
      formattedDate: "", // 用于存储格式化后的日期
      query: {
        title: "",
        current: 1,
        size: 10,
      },
      totalCount: 0,
      tableData: [],
      ruleForm: {
        title: "",//名称
        // location:"",//上传文件 id
        content: '',
        type: "",
        id: ""
      },
      rules: {
        title: [
          {required: true, message: "请输入标题", trigger: "blur"},
        ],
        content: [
          {required: true, message: "请输入数据项", trigger: "blur"},
        ],
        type: [
          {required: true, message: "请输入数据项", trigger: "change"}
        ]
      },
      fileList: [],
    };
  },
  mounted() {
    this.getlist();
    this.getZxtypeFn()
    this.getissjj()
  },
  methods: {
    getuuid() {
      this.uuid = this.guid()
    },
    guid() {
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = Math.random() * 16 | 0,
          v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
      });
    },
    getissjj() {
      issjj().then(res => {
        console.log(res, '是否管理员')
        if (res.msg === '1') {
          this.isShow = true
        } else if (res.msg === '0') {
          this.isShow = false
        }
      })
    },
    editArticle(row) {
      this.ids = row.id
      console.log(row, "编辑回显")
      this.dialogFormVisibleXz = true
      this.dialogTitle = "编辑"
      getZxDetail({id: row.id}).then(res => {
        console.log(res, "编辑回显")
        this.ruleForm.title = res.title;
        this.ruleForm.content = res.content;
        this.ruleForm.type = res.type;
        this.fileList = res.list.map((url) => ({
          name: url.name,  // Use the full URL as the name for display
          id: url.id,   // The full URL for the file
        }));
      })
    },
    delBtn(row) {
      this.$confirm('确定要删除吗？', '提示', {
        type: 'warning'
      })
        .then(() => {
          getZxDelete({id: row.id}).then(res => {
            console.log(res, "删除")
            this.$message.success('删除成功');
            this.getlist()
          })

        })
        .catch(() => {
        });
    },
    getZxtypeFn() {
      getZxtype().then(res => {
        console.log(res, "123123")
        this.options = res
      })
    },
    zxAdd() {
      this.dialogFormVisibleXz = true;
      this.dialogTitle = "新增"
      this.ruleForm = {}
      this.fileList = []
      // 点击新增弹窗 生成uuid
      this.getuuid()
    },
    // 跳转详情
    routerDetails(row) {
      const id = row.id; // 要传递的 ID 参数
      const url = this.$router.resolve({
        name: 'newsInformationDetails',
        query: {id: id}
      }).href;
      window.open(url, '_blank'); // 在新窗口中打开路由
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.dialogTitle == "新增") {
            const formattedRuleForm = {
              ...this.ruleForm,
              id: this.uuid
            };
            getZxadd(formattedRuleForm).then((res) => {
              console.log(res, "新增");
              this.$message({
                message: res.msg,
                type: "success",
              });
              this.fileList = [];
              this.fileLocations = []
              this.dialogFormVisibleXz = false;
              this.resetForm('ruleForm');
              this.getlist()
            });
          }
          if (this.dialogTitle == "编辑") {
            const formattedRuleForm = {
              content: this.ruleForm.content,
              location: this.ruleForm.location,
              id: this.ids
            };
            getZxEdit(formattedRuleForm).then((res) => {
              console.log(res, "编辑");
              this.$message({
                message: res.msg,
                type: "success",
              });
              this.fileList = [];
              this.fileLocations = []
              this.dialogFormVisibleXz = false;
              this.resetForm('ruleForm');
              this.getlist()
            });
          }
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    handlePreview(file) {
      //   文件下载
      if (file.response) {
        this.fileDelId = file.response.id
      } else {
        this.fileDelId = file.id
      }
      this.$axios({
        url: xhDomain + `/api/dataFile/downloadFile/${this.fileDelId}`,
        method: 'post',
        responseType: 'blob', // 确保响应是二进制数据
        headers: {
          'Content-Type': 'application/json',
          "Authorization": JSON.parse(localStorage.getItem('token'))
        },
      }).then((res) => {
        console.log(res, 'res')
        const blob = new Blob([res.data], {type: 'application/octet-stream'});
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = file.name; // 设置下载文件的文件名，可以根据需要修改
        document.body.appendChild(a);
        a.click();
        setTimeout(() => {
          document.body.removeChild(a);
          window.URL.revokeObjectURL(url);
        }, 100);
      }).catch((err) => {
        console.log(err, "err")
        // responseType: 'blob' 这个类型获取报错提示
        if (err.response.data.type === 'application/json') {
          const fileReader = new FileReader();
          fileReader.readAsText(err.response.data, 'utf-8');
          fileReader.onload = function () {
            const result = JSON.parse(fileReader.result);
            console.log(result, 'result');
            this.$message.error(result.message);
          }.bind(this); // Bind `this` to the onload function
          return;
        }

        const content = err.data
        const blob = new Blob([content], {
          type: "application/octet-stream"
        }) //构造一个blob对象来处理数据
        // this.$message.error(err.response.message)
      })

    },
    handleRemove(file, fileList) {
      console.log(file);
      console.log(fileList);
      console.log(file, 'delfile');
      console.log(fileList, 'delfilelist');
      this.$axios({
        url: xhDomain + `/api/dataFile/deleteDataFile/${this.fileDelId}`,
        method: 'post',
        responseType: 'blob', // 确保响应是二进制数据
        headers: {
          'Content-Type': 'application/json',
          "Authorization": JSON.parse(localStorage.getItem('token'))
        },
      }).then((res) => {
        console.log(res, "删除文件")
      })
      // if(this.dialogTitle == '新增'){
      //   // this.ruleForm.location = fileList.map(f => f.response.location).join(',');
      //   // 获取要移除的文件URL
      //   const fileUrlToRemove = xhDomain + `/api/dataFile/downloadFile/${file.response.id}`;
      //
      //   // 从 appIcon 中移除对应的文件URL
      //   const fileUrls = this.ruleForm.location.split(',');
      //   const index = fileUrls.indexOf(fileUrlToRemove);
      //
      //   if (index !== -1) {
      //     fileUrls.splice(index, 1);  // 移除文件URL
      //     this.ruleForm.location = fileUrls.join(',');  // 重新更新 appIcon
      //   }
      // }
      // if(this.dialogTitle == '编辑'){
      //   // debugger;
      //   let locationArr = []
      //   fileList.map((item)=>{
      //     if(item.response){
      //       let fileUrl = xhDomain + `/api/dataFile/downloadFile/${file.response.id}`;
      //       locationArr.push(fileUrl);
      //     }else {
      //       locationArr.push(item.url)
      //     }
      //   })
      //   this.ruleForm.location = locationArr.join(',');  // 重新更新 appIcon
      // }


      //console.log(this.ruleForm.location, 'this.ruleForm.location删除后');
    },
    handleSuccess(res, file) {
      console.log(res, 'res上传成功')
      // 将当前文件的 URL 拼接到 this.ruleForm.appIcon 中
      // const fileUrl = xhDomain + `/api/dataFile/downloadFile/${res.id}`;
      //
      // // 如果 this.ruleForm.appIcon 已经有值，则用逗号分隔并追加新文件URL
      // if (this.ruleForm.location) {
      //   this.ruleForm.location += ',' + fileUrl;
      // } else {
      //   this.ruleForm.location = fileUrl;
      // }
      //
      // console.log(this.ruleForm.location, 'this.ruleForm.location123123');
    },
    beforeRemove(file, fileList) {
      if (file.response) {
        // 新增上传
        this.fileDelId = file.response.id
      } else {
        //编辑
        this.fileDelId = file.id
      }
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    handleExceed(files, fileList) {
      // this.$message.warning(`最多只能上传1个文件`);
      // this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeUpload(file) {
      // this.uploading = true; // 开始上传时显示进度条
      // this.progress = 0; // 重置进度条
      // this.uploadStatus = ''; // 重置上传状态
    },
    handleProgress(event, file, fileList) {
      // this.progress = Math.round(event.percent); // 更新进度条
    },
    handleError(err, file, fileList) {
      console.error('Upload error:', err, file, fileList);
      // this.uploading = false; // 隐藏进度条
      // this.progress = 0; // 重置进度条
      // this.uploadStatus = 'exception'; // 设置上传状态为异常
      this.$message.error('上传失败，请重试'); // 显示错误提示信息
    },
    getCurrentDate() {
      // 创建一个新的 Date 对象来获取当前日期和时间
      const now = new Date();

      // 使用字符串模板字面量和日期对象的方法来格式化日期
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, "0"); // 月份从 0 开始，所以需要 +1 并填充 0
      const day = String(now.getDate()).padStart(2, "0"); // 日期填充 0

      // 更新 data 中的 formattedDate
      this.formattedDate = `${year}/${month}/${day}`;
    },
    handleSizeChange(val) {
      this.query.size = val;
      this.getlist();
    },
    handleCurrentChange(val) {
      this.query.current = val;
      this.getlist();
    },
    getlist() {
      getZxList(this.query).then((res) => {
        console.log(res, "list");
        this.tableData = res.content;
        this.totalCount = res.totalElements;
      });
    },
    search() {
      this.query.current = 1;
      this.getlist();
    },
  },
};
</script>
<style lang="less" scoped>
.lists_tit {
  p {
    font-size: 17px;
    color: #256cd9;
    height: 40px;
    line-height: 40px;
    border-bottom: 1px solid #e6e6e6;
  }
}

.lists-box {
  display: flex;
  justify-content: space-between;
  margin: 15px 0;

  .list_title {
    font-size: 18px;
    border-bottom: 2px solid #149bff;

    span {
      color: #149bff;
    }
  }

  .input-with-select {
    width: 50%;
  }
}

.el-table {
  // margin-top: 15px;
  border-top: 1px solid #ededed;
}
</style>

